<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table'
import type { scmGoodsData } from '#/views/backend/scmGoods/config'

import { onUnmounted, ref, watch } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import {Button, Input, message, Popconfirm, Space, Tag} from 'ant-design-vue'
import dayjs from 'dayjs'

import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { cutedOrderAgainst, cutedOrderApproval, cutedOrderDel, getCutedOrder } from '#/api/cutedOrder'

import productOrder from './productOrder/popupForm.vue'

//  按钮的禁用状态
const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'order_no',
      label: '裁床单号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'SupplyNa',
      label: '工厂',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '成品#首单',
            value: '8',
          },
          {
            label: '加工#补单',
            value: '9',
          },
          {
            label: '加工#首单',
            value: '10',
          },
          {
            label: '成品#补单',
            value: '11',
          },
          {
            label: '成品#加单',
            value: '12',
          },
          {
            label: '加工#加单',
            value: '13',
          },
          { label: '待买手拆分', value: '99' },
        ],
        showSearch: true,
        operator: '123',
      },
      fieldName: 'goodsPurchase*purchase_type',
      operator: 'IN',
      label: '采购性质',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'productOrder*production_sn',
      label: '生产编号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'goods_no',
      label: '货号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'goods_purchase_sn',
      label: '采购单号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'admin*realname',
      label: '制单人',
      operator: 'LIKE',
    },
    {
      component: 'RangePicker',
      componentProps: {
        // 让占位文字更明显
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
      fieldName: 'create_time',
      operator: 'RANGE',
      label: '录入时间',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '完成',
            value: 1,
          },
          {
            label: '未完成',
            value: 0,
          },
        ],
        showSearch: true,
      },
      fieldName: 'is_post',
      operator: '=',
      label: '是否审核',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '已审核',
            value: 1,
          },
          {
            label: '未审核',
            value: 0,
          },
        ],
        showSearch: true,
      },
      fieldName: 'goodsPurchase*is_completed_warehouse',
      operator: '=',
      label: '分仓审核',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}

const gridOptions: VxeTableGridOptions<scmGoodsData> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  height: 'auto',
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    {
      field: 'id',
      title: '下单人',
    },
    { title: '裁床单号', field: 'order_no', width: 160 },
    { title: '数量', field: 'cuted_num', width: 80 },
    { title: '工厂', field: 'SupplyNa', width: 160, slots: { default: 'SupplyNa' } },
    {
      title: '采购性质',
      field: 'purchase_type',
      slots: { default: 'purchase_type' },
    },
    {
      field: 'productOrder.production_sn',
      title: '生产编号',
      slots: { default: 'production_sn' },
    },
    {
      field: 'goods_no',
      title: '货号',

      slots: { default: 'goods_no' },
    },
    {
      field: 'goods_purchase_sn',
      title: '采购单号',
      slots: { default: 'goods_purchase_sn' },
    },
    {
      field: 'admin.realname',
      title: '制单人',

      slots: { default: 'realname' },
    },
    {
      field: 'create_time',
      title: '录入时间',
      slots: { default: 'create_time' },
    },
    {
      title: '是否审核',
      field: 'is_post',
      width: 100,
      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已完成',
            value: 1,
          },
          { color: 'error', label: '未完成', value: 0 },
        ],
      },
    },
    {
      title: '分仓审核',
      field: 'goodsPurchase.is_completed_warehouse',

      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已完成',
            value: 1,
          },
          { color: 'error', label: '未完成', value: 0 },
        ],
      },
    },
    {
      field: 'update_time',
      title: '更新时间',

      slots: { default: 'update_time' },
    },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',

      slots: { default: 'action' },
    },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        // 1. 过滤空值
        const search: any[] = await gridApi.formApi.getFiltersValues()

        // 2. 调接口
        const res = await getCutedOrder({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          is_delete: '0',
          tableSize: 'small',
          quick_search: quick_search.value,
        })
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },
  id: 'cuted_order',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
  rowClassName({ row }) {
    // 如果posted ==0 就是红色字体
    return row.posted === 0 ? 'text-red-500' : ''
  },
}

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions })

// 在数据刷新后重新检查选中状态
function onRefresh() {
  gridApi.query()
}

const isDeleteDisabled = ref(true)
const isApprovalDisabled = ref(true)
const isDisabled = ref(true)
function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()
      // 检查是否包含已财务标记的记录
      const hasApprovalCondition = selectedRecords.some(
        (post: any) =>
          (post.posted !== undefined && post.post_time !== undefined && post.post_time === null) || // 单据
          post.Posted === 0 ||
          (post.posted !== undefined && post.post_time !== undefined && post.post_time === 0) ||
          (post.posted !== undefined && post.posted === 0) ||
          (post.state !== undefined && post.state === 10)
      )
      isApprovalDisabled.value = !hasApprovalCondition
      isDisabled.value = !selectedRecords.some((post: any) => post.posted !== 0 && post.post_time !== 0)
      isDeleteDisabled.value = !selectedRecords || selectedRecords.length === 0 || !hasApprovalCondition
    } else {
      isDisabled.value = true
      isApprovalDisabled.value = true
      isDeleteDisabled.value = true
    }
  } catch {
    isDisabled.value = true
    isApprovalDisabled.value = true
    isDeleteDisabled.value = true
  }
}

watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true }
)

function againstShow() {
  const data = gridApi.grid.getCheckboxRecords()
  const ids = data.map((item: any) => item.id)
  cutedOrderAgainst({ ids }).then((res: any) => {
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    gridApi.reload()
    message.success('审核成功')
  })
}

function approvalBut() {
  const data = gridApi.grid.getCheckboxRecords()
  const ids = data.map((item: any) => item.id)
  cutedOrderApproval({ ids, is_confirm_ware: '0' }).then((res: any) => {
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    gridApi.reload()
    message.success(res.data.msg)
  })
}

function delRow(row?: any) {
  let ids = []
  if (row.id) {
    ids = [row]
  } else {
    const data = gridApi.grid.getCheckboxRecords()
    ids = data.map((item: any) => item.id)
  }
  cutedOrderDel({ ids }).then((res: any) => {
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    gridApi.reload()
    message.success(res.data.msg)
  })
}

const [productOrderModal, productOrderModalApi] = useVbenModal({
  connectedComponent: productOrder,
  destroyOnClose: true,
})
function openModal(res: any, but: string) {
  productOrderModalApi.setData({ rowData: res, view: but }).open()
}

/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}
</script>

<template>
  <Page auto-content-height>
    <productOrderModal />
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space>
            <Button type="primary" @click="openModal('', 'add')">新建</Button>
            <Button type="primary" danger :disabled="isDeleteDisabled" title="删除选中行" @click="delRow">删除</Button>
            <Popconfirm title="确定审核选中记录" ok-text="确认" cancel-text="取消" @confirm="approvalBut()">
              <Button type="primary" title="审核选中行" :disabled="isApprovalDisabled">审核</Button>
            </Popconfirm>
            <Button type="primary" danger :disabled="isDisabled" @click="againstShow()">反审</Button>
          </Space>
        </div>
      </template>
      <template #toolbar-tools>
        <Input v-model:value="quick_search" allow-clear placeholder="通过采购单号、简码、货号、制单号、裁床单号快速搜索" style="width: 400px; margin-right: 8px" @change="doSearch" />
      </template>
      <template #SupplyNa="{ row }">
        <Tag color="blue">{{ row.SupplyNa }}</Tag>
      </template>
      <template #realname="{ row }">
        <Tag color="blue">{{ row.admin.realname }}</Tag>
      </template>
      <template #production_sn="{ row }">
        <Tag color="blue">{{ row.productOrder.production_sn }}</Tag>
      </template>
      <template #goods_no="{ row }">
        <Tag color="blue">{{ row.goods_no }}</Tag>
      </template>
      <template #goods_purchase_sn="{ row }">
        <Tag color="blue">{{ row.goods_purchase_sn }}</Tag>
      </template>
      <template #purchase_type="{ row }">
        <Tag v-if="row.goodsPurchase?.purchase_type === 8" color="green">成品#首单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 9" color="red">加工#补单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 10" color="blue">加工#首单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 11" color="blue">成品#补单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 12" color="blue">成品#加单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 13" color="blue">加工#加单</Tag>
        <Tag v-else-if="row.goodsPurchase?.purchase_type === 99" color="blue">待买手拆分</Tag>
      </template>
      <template #create_time="{ row }">
        {{ dayjs.unix(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #update_time="{ row }">
        {{ dayjs.unix(row.update_time).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <Space>
          <Popconfirm title="确定删除选中记录？" ok-text="确认" cancel-text="取消" @confirm="delRow(row)">
            <Button type="primary" title="删除" danger size="small">删除</Button>
          </Popconfirm>
          <Button type="primary" size="small" @click="openModal(row, 'edit')">编辑</Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
<style lang="scss" scoped>
.my-green-btn.ant-btn-primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.my-yello-btn.ant-btn-primary {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
</style>
